﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.IO;
using System.Runtime.InteropServices;
using System.Configuration;
using System.Security.Principal;
using System.Runtime.Serialization;
using VietPublisher.BaseProject.Utils.Miscellaneous;
using System.ComponentModel;

using Ionic.Zip;
//using Telerik.Web.UI;

using BOOL = System.Boolean;
using DWORD = System.UInt32;
using LPWSTR = System.String;
using NET_API_STATUS = System.UInt32;


namespace VietPublisher.FileManager
{
    public class FileUtility : IDisposable
    {
        private UNCAccessWithCredentials uncAccess = null;
        private UNCAccessWithCredentials uncAccess1 = null;

       
        
        VietPublisherEntities_FileManager entities;

        public FileUtility()
        {
            entities = new VietPublisherEntities_FileManager();
        }

        /// <summary>
        /// WHen download, reading real file, set accessFile to true
        /// </summary>
        /// <param name="accessFile"></param>
        public FileUtility(bool accessFile)
        {
            entities = new VietPublisherEntities_FileManager();
            if (accessFile)
            {
                ImpersonateUser();
            }
        }


        public string GetLocation(string key)
        {
            string storeDirectory = ConfigurationManager.AppSettings[key].ToString();

            if (storeDirectory.Contains("~"))
            {
                storeDirectory = System.Web.HttpContext.Current.Server.MapPath(storeDirectory);
            }

            return storeDirectory;
        }

        #region Impersonate to access remote file

        /// <summary>
        /// 
        /// </summary>
        private void ImpersonateUser()
        {
            // impersonate..
            string storeDirectory = ConfigurationManager.AppSettings[DConst.uploadLocationKey].ToString();
            string hrDirectory = ConfigurationManager.AppSettings[DConst.hrDataLocationKey].ToString();

            if (!storeDirectory.StartsWith("\\") && !hrDirectory.StartsWith("\\"))
            {
                return;
            }

            uncAccess = new UNCAccessWithCredentials();
            bool connected = uncAccess.NetUseWithCredentials(storeDirectory, FileConfigure.GW_ADMIN, FileConfigure.DOMAIN_NAME, FileConfigure.GW_ADMIN_PWD);

            uncAccess1 = new UNCAccessWithCredentials();
            connected = uncAccess.NetUseWithCredentials(hrDirectory, FileConfigure.GW_ADMIN, FileConfigure.DOMAIN_NAME, FileConfigure.GW_ADMIN_PWD);
            
        }

        void IDisposable.Dispose()
        {
            if (uncAccess != null)
            {
                uncAccess.NetUseDelete();
            }

            if (uncAccess1 != null)
            {
                uncAccess1.NetUseDelete();
            }
        }

        #endregion

        #region Privates

        private string GetFileSize(decimal sizeInByte)
        {
            if (sizeInByte >= 1024)
            {
                if (sizeInByte >= 1024 * 1024)
                {
                    return (sizeInByte / (1024 * 1024)).ToString("#,##0.##") + " MB";
                }
                return (sizeInByte / 1024).ToString("#,##0.##") + " KB";
            }
            return sizeInByte.ToString("#,##0.##") + " Bytes";
        }

        private string GetFilePath(Guid fileId)
        {
            var file = entities.T_SC_FileList.FirstOrDefault(p => p.FileId == fileId);
            if (file != null)
            {
                return file.PhysicalPath;
            }
            return string.Empty;
        }

        /// <summary>
        /// Make file folder path only
        /// </summary>
        /// <param name="groupId"></param>
        /// <returns></returns>
        private string MakeFilePath(int groupId)
        {
            string parentFolder = GetLocation(DConst.uploadLocationKey);
            if (parentFolder.Contains("~"))
            {
                parentFolder = System.Web.HttpContext.Current.Server.MapPath(parentFolder);
            }

            string path = parentFolder + "\\" + DateTime.Today.ToString("yyyyMM") + "\\Group_" + groupId.ToString() + "\\";

            try
            {
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }

            }
            catch (Exception ex)
            {
                LogUtility.LogMessage("FileUtility","MakeFilePath",ex.Message);
            }

            return path;
        }

        /// <summary>
        /// make file full path, create folder if not exists
        /// </summary>
        /// <param name="groupId"></param>
        /// <param name="fileNameNoExt"></param>
        /// <param name="fileExt"></param>
        /// <returns></returns>
        private string MakeFilePath(int groupId, Guid fileId, string fileNameNoExt, string fileExt)
        {
            string path = MakeFilePath(groupId);
            string fileName = fileId.ToString() + "_" + fileNameNoExt + fileExt;

            try
            {
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }

            }
            catch (Exception ex)
            {
                LogUtility.LogMessage("FileUtility", "MakeFilePath", ex.Message);
            }


            return Path.Combine(path, fileName);
        }

        public byte[] GetFileStream(string filePath)
        {
            byte[] buffer;
            FileStream fileStream;
            try
            {
                fileStream = new FileStream(    ConfigurationManager.AppSettings["AbsolutePath"].ToString()+filePath, FileMode.Open, FileAccess.Read);
            }
            catch (FileNotFoundException)
            {
                return null;
            }
            try
            {
                int length = (int)fileStream.Length;
                buffer = new byte[length];
                int count;
                int sum = 0;

                while ((count = fileStream.Read(buffer, sum, length - sum)) > 0)
                {
                    sum += count;
                }
            }
            finally
            {
                fileStream.Close();
            }
            return buffer;
        }

        public string RemoveGuidString(string fileName)
        {
            try
            {
                fileName = fileName.Substring(Guid.Empty.ToString().Length + 1);
            }
            catch
            {
            }
            return fileName;
        }

        /// <summary>
        /// Get or create a new group 
        /// </summary>
        /// <param name="groupId"></param>
        /// <param name="groupName"></param>
        /// <returns></returns>
        private T_SC_FileGroup GetOrCreateGroup(int? groupId, string groupName)
        {
            var group = entities.T_SC_FileGroup.FirstOrDefault(p => p.GroupId == groupId && groupId != 0);
            if (group == null)
            {
                group = new T_SC_FileGroup()
                {
                    Name = groupName,
                    Description = string.Empty
                };

                entities.AddToT_SC_FileGroup(group);
                entities.SaveChanges();
                entities.Refresh(System.Data.Objects.RefreshMode.ClientWins, group);
            }

            return group;
        }

        private T_SC_FileGroup GetOrCreateGroup(int? groupId, string groupName, string groupDesc)
        {
            var group = entities.T_SC_FileGroup.FirstOrDefault(p => p.GroupId == groupId && groupId != 0);
            if (group == null)
            {
                group = new T_SC_FileGroup()
                {
                    Name = groupName,
                    Description = groupDesc
                };

                entities.AddToT_SC_FileGroup(group);
                entities.SaveChanges();
                entities.Refresh(System.Data.Objects.RefreshMode.ClientWins, group);
            }

            return group;
        }

        /// <summary>
        /// Get files of a group
        /// </summary>
        /// <param name="groupId"></param>
        /// <returns></returns>
        private T_SC_FileList[] GetFilesByGroup(int groupId)
        {
            return entities.T_SC_FileList.Where(p => p.GroupId == groupId).OrderBy(p => p.UpOrder).ToArray();
        }

        #endregion

        #region Public

        /// <summary>
        /// Save uploaded file into group
        /// </summary>
        /// <param name="file"></param>
        /// <param name="groupId"></param>
        /// <returns></returns>
        public Guid SaveUploadedFile(HttpPostedFileBase file, int groupId)
        {
            if (file != null)
            {
                if (file.ContentLength > 0)
                {
                    string name = Path.GetFileNameWithoutExtension(file.FileName);
                    string ext = Path.GetExtension(file.FileName);
                    Guid fileId = Guid.NewGuid();
                    string fileName = MakeFilePath(groupId, fileId, name, ext);
                    file.SaveAs(fileName);

                    var group = GetOrCreateGroup(groupId, string.Empty);

                    int? maxOrder = entities.T_SC_FileList.Where(p => p.GroupId == group.GroupId).Max(p => p.UpOrder);
                    maxOrder = maxOrder ?? 0;

                    var fileItem = new T_SC_FileList();
                    fileItem.FileId = fileId;
                    fileItem.UpOrder = maxOrder + 1;
                    fileItem.Name = name;
                    fileItem.Ext = ext;
                    fileItem.Size = file.ContentLength;
                    fileItem.PhysicalPath = fileName;
                    fileItem.GroupId = group.GroupId;

                    entities.AddToT_SC_FileList(fileItem);
                    entities.SaveChanges();

                    return fileId;
                }
            }
            return Guid.Empty;
        }

        /// <summary>
        /// save from Telerik asynupload component
        /// </summary>
        /// <param name="file"></param>
        /// <param name="groupId"></param>
        /// <returns></returns>
        //public Guid SaveUploadedFile(UploadedFile file, int groupId, string tmpFolder, out int newGroupId)
        //{
        //    newGroupId = groupId;
        //    if (file != null)
        //    {
        //        if (file.ContentLength > 0)
        //        {
        //            var group = GetOrCreateGroup(groupId, string.Empty);
        //            newGroupId = group.GroupId;

        //            string name = Path.GetFileNameWithoutExtension(file.FileName);
        //            string ext = Path.GetExtension(file.FileName);
        //            Guid fileId = Guid.NewGuid();

        //            string fileName = MakeFilePath(newGroupId, fileId, name, ext);

        //            // tmp file
        //            string fullPath = Path.Combine(tmpFolder, file.FileName);

        //            // move to target
        //            file.SaveAs(fileName);
        //            FileInfo fi = new FileInfo(fileName);

        //            int? maxOrder = entities.T_SC_FileList.Where(p => p.GroupId == group.GroupId).Max(p => p.UpOrder);
        //            maxOrder = maxOrder ?? 0;

        //            var fileItem = new T_SC_FileList();
        //            fileItem.FileId = fileId;
        //            fileItem.UpOrder = maxOrder + 1;
        //            fileItem.Name = name;
        //            fileItem.Ext = ext;
        //            fileItem.Size = fi.Length;
        //            fileItem.PhysicalPath = fileName;
        //            fileItem.GroupId = group.GroupId;

        //            entities.AddToT_SC_FileList(fileItem);
        //            entities.SaveChanges();

        //            return fileId;
        //        }
        //    }
        //    return Guid.Empty;
        //}

        /// <summary>
        /// Move file to tmp folder to target folder and rename file name
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="groupId"></param>
        /// <param name="tmpFolder"></param>
        /// <param name="newGroupId"></param>
        /// <returns></returns>
        public Guid SaveUploadedFile(string filePath, int groupId, out int newGroupId)
        {
            newGroupId = groupId;
            
            if (File.Exists(filePath))
            {
                var group = GetOrCreateGroup(groupId, string.Empty);
                newGroupId = group.GroupId;

                Guid fileId = Guid.NewGuid();
                string name = Path.GetFileNameWithoutExtension(filePath);
                name = RemoveGuidString(name);

                string ext = Path.GetExtension(filePath);
                string targetFilePath = MakeFilePath(newGroupId, fileId, name, ext);
                                
                // move to target
                File.Move(filePath, targetFilePath);
                FileInfo fi = new FileInfo(targetFilePath);

                int? maxOrder = entities.T_SC_FileList.Where(p => p.GroupId == group.GroupId).Max(p => p.UpOrder);
                maxOrder = maxOrder ?? 0;

                var fileItem = new T_SC_FileList();
                fileItem.FileId = fileId;
                fileItem.UpOrder = maxOrder + 1;
                fileItem.Name = name;
                fileItem.Ext = ext;
                fileItem.Size = fi.Length;
                fileItem.PhysicalPath = targetFilePath;
                fileItem.GroupId = group.GroupId;

                entities.AddToT_SC_FileList(fileItem);
                entities.SaveChanges();

                return fileId;
            }
            return Guid.Empty;
        }

        /// <summary>
        /// Move file to tmp folder to target folder and rename file name
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="groupId"></param>
        /// <param name="tmpFolder"></param>
        /// <param name="newGroupId"></param>
        /// <returns></returns>
        public int CopyUploadedFile(string filePath, int groupId, out int newGroupId)
        {
            newGroupId = groupId;

            if (File.Exists(filePath))
            {
                var group = GetOrCreateGroup(groupId, string.Empty);
                newGroupId = group.GroupId;

                Guid fileId = Guid.NewGuid();
                string name = Path.GetFileNameWithoutExtension(filePath);
                name = RemoveGuidString(name);

                string ext = Path.GetExtension(filePath);
                string targetFilePath = MakeFilePath(newGroupId, fileId, name, ext);

                // move to target
                File.Copy(filePath, targetFilePath);
                FileInfo fi = new FileInfo(targetFilePath);

                int? maxOrder = entities.T_SC_FileList.Where(p => p.GroupId == group.GroupId).Max(p => p.UpOrder);
                maxOrder = maxOrder ?? 0;

                var fileItem = new T_SC_FileList();
                fileItem.FileId = fileId;
                fileItem.UpOrder = maxOrder + 1;
                fileItem.Name = name;
                fileItem.Ext = ext;
                fileItem.Size = fi.Length;
                fileItem.PhysicalPath = targetFilePath;
                fileItem.GroupId = group.GroupId;

                entities.AddToT_SC_FileList(fileItem);
                entities.SaveChanges();

                return newGroupId;
            }
            return 0;
        }

        /// <summary>
        /// Save a new file, and return a group id
        /// 
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="groupId"></param>
        /// <param name="groupName"></param>
        /// <param name="groupDesc"></param>
        /// <param name="newGroupId"></param>
        /// <returns></returns>
        public Guid SaveUploadedFile(string filePath, int groupId, string groupName, string groupDesc, out int newGroupId)
        {
            newGroupId = groupId;

            if (File.Exists(filePath))
            {
                var group = GetOrCreateGroup(groupId, groupName, groupDesc);
                newGroupId = group.GroupId;

                Guid fileId = Guid.NewGuid();
                string name = Path.GetFileNameWithoutExtension(filePath);
                name = RemoveGuidString(name);

                string ext = Path.GetExtension(filePath);
                string targetFilePath = MakeFilePath(newGroupId, fileId, name, ext);

                // move to target
                File.Move(filePath, targetFilePath);
                FileInfo fi = new FileInfo(targetFilePath);

                int? maxOrder = entities.T_SC_FileList.Where(p => p.GroupId == group.GroupId).Max(p => p.UpOrder);
                maxOrder = maxOrder ?? 0;

                var fileItem = new T_SC_FileList();
                fileItem.FileId = fileId;
                fileItem.UpOrder = maxOrder + 1;
                fileItem.Name = name;
                fileItem.Ext = ext;
                fileItem.Size = fi.Length;
                fileItem.PhysicalPath = targetFilePath;
                fileItem.GroupId = group.GroupId;

                entities.AddToT_SC_FileList(fileItem);
                entities.SaveChanges();

                return fileId;
            }
            return Guid.Empty;
        }

        /// <summary>
        /// Download file into zip
        /// </summary>
        /// <param name="fileIds"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public string DownloadFile(Guid[] fileIds, out byte[] data)
        {
            string fileName = string.Empty;
            data = null;
            if (fileIds.Length == 1)
            {
                var file = GetFileInfo(fileIds[0]);
                if (file != null)
                {
                    data = GetFileStream(file.PhysicalPath);
                    fileName = file.Name + file.Ext;
                }
            }
            else
            {
                List<string> fileList = GetFileList(fileIds);
                if (fileList != null)
                {
                    var zip = new ZipFile();
                    zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestCompression;
                    zip.ProvisionalAlternateEncoding = Encoding.UTF8;
                    foreach (string file in fileList)
                    {
                        if (File.Exists(file))
                        {
                            string entryName = RemoveGuidString(Path.GetFileName(file));
                            byte[] content = File.ReadAllBytes(file);
                            try
                            {
                                zip.AddEntry(entryName, content);
                            }
                            catch (ArgumentException ex)
                            {
                                if (ex.Message.ToLower() == "an item with the same key has already been added.")
                                {
                                    entryName = Path.GetFileNameWithoutExtension(entryName) + "_" + fileList.IndexOf(file).ToString() + Path.GetExtension(entryName);
                                    zip.AddEntry(entryName, content);
                                }
                            }
                        }
                    }
                    MemoryStream output = new MemoryStream();
                    zip.Save(output);
                    data = output.ToArray();
                    fileName = "Download.zip";
                }
            }
            return fileName;
        }

        /// <summary>
        /// Download files into zip
        /// </summary>
        /// <param name="files"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public string DownloadStructuralFile(Dictionary<string, string> files, out byte[] data)
        {
            data = null;
            string[] keys = (from p in files
                             select p.Key).ToArray();

            T_SC_FileList[] fileArray = new T_SC_FileList[keys.Length];
            for (int i = 0; i < keys.Length; i++)
            {
                Guid fileId = new Guid(keys[i].Split('_')[1]);
                var file = GetFileInfo(fileId);

                if (file != null)
                {
                    fileArray[i] = file;
                }
            }

            var zip = new ZipFile();
            zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestCompression;
            zip.ProvisionalAlternateEncoding = Encoding.UTF8;
            for (int i = 0; i < fileArray.Length; i++)
            {
                if (File.Exists(fileArray[i].PhysicalPath))
                {
                    string entryName = RemoveGuidString(Path.GetFileName(fileArray[i].PhysicalPath));
                    string path = (from p in files
                                   where p.Key == i.ToString() + "_" + fileArray[i].FileId.ToString()
                                   select p.Value
                                   ).FirstOrDefault();
                    byte[] content = File.ReadAllBytes(fileArray[i].PhysicalPath);
                    try
                    {
                        zip.AddEntry(path + entryName, content);
                    }
                    catch (ArgumentException ex)
                    {
                        if (ex.Message.ToLower() == "an item with the same key has already been added.")
                        {
                            entryName = Path.GetFileNameWithoutExtension(entryName) + "_" + i.ToString() + Path.GetExtension(entryName);
                            zip.AddEntry(path + entryName, content);
                        }
                    }
                }
            }
            MemoryStream output = new MemoryStream();
            zip.Save(output);
            data = output.ToArray();
            return "Download.zip";
        }

        /// <summary>
        /// Download all files of group
        /// </summary>
        /// <param name="groupId"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public string DownloadFile(int groupId, out byte[] data)
        {
            string fileName = string.Empty;
            data = null;
            var files = GetFilesByGroup(groupId);
            if (files != null)
            {
                if (files.Length == 1)
                {
                    data = GetFileStream(files[0].PhysicalPath);
                    fileName = files[0].Name + files[0].Ext;
                }
                else
                {
                    var zip = new ZipFile(Encoding.UTF8);
                    zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestCompression;
                    List<string> fileList = new List<string>();
                    for (int i = 0; i < files.Length; i++)
                    {
                        if (File.Exists(files[i].PhysicalPath))
                        {
                            byte[] content = File.ReadAllBytes(files[i].PhysicalPath);
                            zip.AddEntry(RemoveGuidString(Path.GetFileName(files[i].PhysicalPath)), content);
                        }
                    }
                    MemoryStream output = new MemoryStream();
                    zip.Save(output);
                    data = output.ToArray();
                    fileName = "Download.zip";
                }
            }
            return fileName;
        }

        /// <summary>
        /// Download remote file
        /// </summary>
        /// <param name="remoteFilePath"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public bool DownloadFile(string remoteFilePath, out byte[] data)
        {
            // return true, if exists..otherwise false            
            data = GetFileStream(remoteFilePath);
            return data != null;
        }

        /// <summary>
        /// Return file stream
        /// </summary>
        /// <param name="fileId"></param>
        /// <returns></returns>
        public Stream GetFileStream(Guid fileId, out string contentType)
        {
            FileStream fs = null;
            contentType = "application/octet-stream";
            var file = GetFileInfo(fileId);
            if (file != null)
            {
                try
                {
                    contentType = "application/" + Path.GetExtension(file.PhysicalPath).Replace(".", "");
                    fs = File.OpenRead(file.PhysicalPath);
                }
                catch
                {
                }
            }

            return fs;
        }

        /// <summary>
        /// Get file list by id
        /// </summary>
        /// <param name="fileIds"></param>
        /// <returns></returns>
        public List<string> GetFileList(Guid[] fileIds)
        {
            List<string> fileList = new List<string>();
            for (int i = 0; i < fileIds.Length; i++)
            {
                string fileName = GetFilePath(fileIds[i]);
                if (fileName != string.Empty)
                {
                    fileList.Add(fileName);
                }
            }
            return (fileList.Count > 0) ? fileList : null;
        }

        /// <summary>
        /// Get file list from group
        /// </summary>
        /// <param name="groupId"></param>
        /// <returns></returns>
        public string[] GetFileList(int groupId)
        {
            var files = GetFilesByGroup(groupId);
            if (files != null)
            {
                string[] filePathArray = new string[files.Length];
                for (int i = 0; i < files.Length; i++)
                {
                    filePathArray[i] = files[i].PhysicalPath;
                }
                return filePathArray;
            }
            return null;
        }

        /// <summary>
        /// Delete multiple files
        /// </summary>
        /// <param name="fileIds"></param>
        public void DeleteFile(Guid[] fileIds)
        {
            if (fileIds.Length == 0)
            {
                return;
            }

            string parentFolder = string.Empty;

            var firstFileId = fileIds[0];
            var fileInfo = entities.T_SC_FileList.FirstOrDefault(p => p.FileId == firstFileId);
            int groupId = fileInfo != null ? fileInfo.GroupId : 0;
            foreach (Guid fileId in fileIds)
            {
                var file = GetFileInfo(fileId);
                try
                {
                    parentFolder = Path.GetDirectoryName(file.PhysicalPath);
                    File.Delete(file.PhysicalPath);
                }
                catch { }

                DeleteFileInfo(fileId);               
            }

            var count = entities.T_SC_FileList.Count(p => p.GroupId == groupId);
            if (count == 0)
            {
                var group = entities.T_SC_FileGroup.FirstOrDefault(p => p.GroupId == groupId);
                if (group != null)
                {
                    entities.T_SC_FileGroup.DeleteObject(group);
                    entities.SaveChanges();
                }

                try
                {
                    if (Directory.Exists(parentFolder))
                    {
                        Directory.Delete(parentFolder);
                    }
                }
                catch
                {
                }
            }
        }

        /// <summary>
        /// Delete all files in group and real files
        /// </summary>
        /// <param name="groupId"></param>
        public void DeleteFileGroup(int groupId)
        {
            string parentFolder = string.Empty;
            var fileInfos = entities.T_SC_FileList.Where(p => p.GroupId == groupId).ToArray();
            foreach (var fileInfo in fileInfos)
            {
                try
                {
                    parentFolder = Path.GetDirectoryName(fileInfo.PhysicalPath);
                    File.Delete(fileInfo.PhysicalPath);
                }
                catch { }

                entities.T_SC_FileList.DeleteObject(fileInfo);
                entities.SaveChanges();
            }

            try
            {
                if (Directory.Exists(parentFolder))
                {
                    Directory.Delete(parentFolder);
                }
            }
            catch
            {

            }

            // delete file group
            var fileGroup = entities.T_SC_FileGroup.FirstOrDefault(p => p.GroupId == groupId);
            if (fileGroup != null)
            {
                entities.T_SC_FileGroup.DeleteObject(fileGroup);
                entities.SaveChanges();
            }
        }

        /// <summary>
        /// Delete a file
        /// </summary>
        /// <param name="fileId"></param>
        public void DeleteFileInfo(Guid fileId)
        {
            var file = entities.T_SC_FileList.FirstOrDefault(p => p.FileId == fileId);
            if (file != null)
            {
                entities.T_SC_FileList.DeleteObject(file);
                entities.SaveChanges();
            }
        }

        public T_SC_FileList GetFileInfo(Guid fileId)
        {
            return entities.T_SC_FileList.FirstOrDefault(p => p.FileId == fileId);
        }

        public T_SC_FileList[] GetFileListGroup(int groupId)
        {
            return entities.T_SC_FileList.Where(p => p.GroupId == groupId).OrderBy(p => p.UpOrder).ToArray();
        }

        public vw_T_SC_FileList[] GetFileListView(int groupId)
        {
            List<vw_T_SC_FileList> newList = new List<vw_T_SC_FileList>();
            var list = entities.T_SC_FileList.Where(p => p.GroupId == groupId).OrderBy(p => p.UpOrder).ToArray();

            int order = 1;
            foreach (var item in list)
            {
                newList.Add(new vw_T_SC_FileList()
                {
                    No = order,
                    GroupId = item.GroupId,
                    FileId = item.FileId,
                    Name = item.Name,
                    Size = item.Size.Value,
                    FileSize = GetFileSize(item.Size.Value),
                    Ext = item.Ext,
                    PhysicalPath = item.PhysicalPath
                });

                order++;
            }

            return newList.ToArray();
        }

        public int CheckFile(Guid[] fileIds)
        {
            int flag = 0;

            int count = fileIds.Length;
            foreach (Guid fileId in fileIds)
            {
                var file = GetFileInfo(fileId);
                if (file == null)
                {
                    flag++;
                }
                else if (file != null && !File.Exists(file.PhysicalPath))
                {
                    flag++;
                }
            }
            if (flag == 0)
                return 0;
            if (flag == count)
                return 2;
            return 1;
        }

        /// <summary>
        /// Check if a file exists
        /// </summary>
        /// <param name="remoteFilePath"></param>
        /// <returns></returns>
        public bool FileExists(string remoteFilePath)
        {
            return File.Exists(remoteFilePath);
        }

        #endregion

        
    }

}
